<template>
  <div>
    <!-- 物模型操作按钮 -->
    <div class="physical-model-button">

      <!-- 重置协议支持 -->
      <el-badge is-dot type="warning" v-show="protocolStandbyVisible">
        <el-popconfirm
          title="重置后将使用产品的协议支持配置"
          @confirm="handleResetProtocolStandby"
        >
          <el-button
            size="small"
            icon="el-icon-refresh-left"
            v-hasPermi="['iot:device:edit']"
            slot="reference"
          >重置协议
          </el-button>
        </el-popconfirm>
      </el-badge>

      <!-- 重置物模型 -->
      <el-badge is-dot type="warning" v-show="resetMetadataVisible">
        <el-popconfirm
          title="重置后将使用产品的物模型配置"
          @confirm="handleResetMetadata"
        >
          <el-button
            style="margin-left: 10px"
            size="small"
            icon="el-icon-refresh-left"
            v-hasPermi="['iot:device:edit']"
            slot="reference"
          >重置模型
          </el-button>
        </el-popconfirm>
      </el-badge>

      <!-- 查看物模型数据 -->
      <el-button style="margin-left: 10px" size="small" @click="handlePhysicalModelView">物模型TSL</el-button>
    </div>

    <!-- 物模型标签页 -->
    <el-tabs v-model="physicalModelTabsActiveName">

      <!-- 属性定义 -->
      <el-tab-pane label="属性定义" name="properties">

        <!-- 属性定义卡片 -->
        <el-card>
          <!-- 卡片头信息 -->
          <div class="card-header" slot="header">
            <span>属性定义</span>
            <span class="add-button" style="padding-left: 20px">
              <el-button
                icon="el-icon-plus"
                @click="handlePropertiesAdd"
                size="small"
              >添 加
              </el-button>
            </span>
            <el-button
              class="add-button"
              icon="el-icon-bottom"
              type="text"
              size="small"
              @click="handleSetProperties"
            >获 取
            </el-button>
          </div>
          <!-- 属性列表 -->
          <properties-table/>
        </el-card>

      </el-tab-pane>

      <!-- 功能定义 -->
      <el-tab-pane label="功能定义" name="functions">

        <!-- 功能定义卡片 -->
        <el-card>
          <!-- 卡片头信息 -->
          <div class="card-header" slot="header">
            <span>功能定义</span>
            <el-button
              class="add-button"
              icon="el-icon-plus"
              @click="handleFunctionsAdd"
              size="small"
            >添 加
            </el-button>
          </div>
          <!-- 功能列表 -->
          <functions-table/>

        </el-card>

      </el-tab-pane>

      <!-- 事件定义 -->
      <el-tab-pane label="事件定义" name="events">
        <!-- 事件定义卡片 -->
        <el-card>
          <!-- 卡片头信息 -->
          <div class="card-header" slot="header">
            <span>事件定义</span>
            <el-button
              class="add-button"
              icon="el-icon-plus"
              @click="handleEventsAdd"
              size="small"
            >添 加
            </el-button>
          </div>
          <!-- 事件列表 -->
          <events-table/>

        </el-card>

      </el-tab-pane>

      <!-- 标签定义 -->
      <el-tab-pane label="标签定义" name="tags">
        <!-- 事件定义卡片 -->
        <el-card>
          <!-- 卡片头信息 -->
          <div class="card-header" slot="header">
            <span>标签定义</span>
            <el-button
              class="add-button"
              icon="el-icon-plus"
              @click="handleTagsAdd"
              size="small"
            >添 加
            </el-button>
          </div>
          <!-- 标签列表 -->
          <tags-table/>

        </el-card>
      </el-tab-pane>

    </el-tabs>

    <!-- 属性添加或修改对话框 -->
    <properties-add-edit submitType="save" @submit="submitProperties" ref="propertiesAddEdit"/>

    <!-- 功能添加或修改对话框 -->
    <functions-add-edit submitType="save" @submit="submitFunctions" ref="functionsAddEdit" />

    <!-- 事件添加或修改对话框 -->
    <events-add-edit submitType="save" @submit="submitEvents" ref="eventsAddEdit" />

    <!-- 标签添加或修改对话框 -->
    <tags-add-edit submitType="save" @submit="submitTags" ref="tagsAddEdit" />

    <!-- 查看物模型对话框 -->
    <view-physical-model ref="viewPhysicalModel"/>

    <!-- 协议支持对话框 -->
    <protocol-standby @submit="submitProtocolStandby" ref="protocolStandby"/>

  </div>

</template>

<script>

import PropertiesTable from '@/views/iot/device/physical-model/propertiesTable'
import FunctionsTable from '@/views/iot/device/physical-model/functionsTable'
import EventsTable from '@/views/iot/device/physical-model/eventsTable'
import TagsTable from '@/views/iot/device/physical-model/tagsTable'
import ViewPhysicalModel from '@/views/iot/product/physical-model/viewPhysicalModel'
import ProtocolStandby from '@/views/iot/product/physical-model/protocolStandby'
import PropertiesAddEdit from '@/views/iot/product/physical-model/propertiesAddEdit'
import FunctionsAddEdit from '@/views/iot/product/physical-model/functionsAddEdit'
import EventsAddEdit from '@/views/iot/product/physical-model/eventsAddEdit'
import TagsAddEdit from '@/views/iot/product/physical-model/tagsAddEdit'
import {
  getDeviceRealtimeProperties,
  resetMetadata,
  resetProtocolStandby,
  updateMetadata,
  updateProtocolStandby
} from '@/api/iot/device'
import { mapState } from 'vuex'
import utils from '@/utils/iot/metadata'

export default {
  // 物模型页签页
  name: 'PhysicalModel',
  components: {
    // 属性表格组件
    PropertiesTable,
    // 功能表格组件
    FunctionsTable,
    // 事件表格组件
    EventsTable,
    // 标签表格组件
    TagsTable,
    // 查询物模型组件
    ViewPhysicalModel,
    // 属性表单组件
    PropertiesAddEdit,
    // 功能表单组件
    FunctionsAddEdit,
    // 事件表单组件
    EventsAddEdit,
    // 标签表单组件
    TagsAddEdit,
    // 协议支持对话框
    ProtocolStandby
  },
  computed: {
    ...mapState({
      // 设备id
      deviceId: state => state.device.deviceId,
      // 设备详情信息
      deviceDetailInfo: state => state.device.deviceDetailInfo,
      // 详情页显示状态
      detailedPageVisible: state => state.device.detailedPageVisible,
    })
  },
  watch: {
    /**
     * 协议支持的状态
     * true 自治的
     * false 从属产品的
     * */
    'deviceDetailInfo.independentProtocolStandby'(value) {
      this.protocolStandbyVisible = value
    },

    /**
     * 物模型状态
     * true 自治的
     * false 从属产品的
     */
    'deviceDetailInfo.independentMetadata'(value) {
      this.resetMetadataVisible = value
    }
  },
  mounted() {
    this.$store.commit("DEVICE_PROPERTIES_ADD_EDIT", this.$refs.propertiesAddEdit);
    this.$store.commit("DEVICE_FUNCTIONS_ADD_EDIT", this.$refs.functionsAddEdit);
    this.$store.commit("DEVICE_EVENTS_ADD_EDIT", this.$refs.eventsAddEdit);
    this.$store.commit("DEVICE_TAGS_ADD_EDIT", this.$refs.tagsAddEdit);
    this.$store.commit('DEVICE_PROTOCOL_STANDBY', this.$refs.protocolStandby)
  },
  created() {
    // 协议支持的状态 true 自治的 false 从属产品的
    this.protocolStandbyVisible = this.deviceDetailInfo.independentProtocolStandby
    // 物模型状态 true 自治的 false 从属产品的
    this.resetMetadataVisible = this.deviceDetailInfo.independentMetadata
  },
  data() {
    return {
      // 物模型tabs，默认展示属性定义
      physicalModelTabsActiveName: 'properties',
      // 协议支持按钮显示状态
      protocolStandbyVisible: false,
      // 重置物模型按钮显示状态
      resetMetadataVisible: false,
    }
  },
  methods: {

    /** 重置设备协议支持 */
    handleResetProtocolStandby() {
      resetProtocolStandby(this.deviceId).then(() => {
        // 获取设备详情信息
        this.$store.dispatch('GetDeviceDetailInfo', this.deviceId)
      });
    },

    /** 重置设备物模型 */
    handleResetMetadata() {
      resetMetadata(this.deviceId).then(() => {
        // 获取设备详情信息
        this.$store.dispatch('GetDeviceDetailInfo', this.deviceId)
      });
    },

    /** 属性添加按钮操作 */
    handlePropertiesAdd() {
      this.$refs.propertiesAddEdit.handleAdd();
    },

    /** 批量获取属性 */
    handleSetProperties() {
      const properties = JSON.parse(this.deviceDetailInfo.metadata).properties
      const deviceId = this.deviceId
      let props = {
        headers: {
          // 设备异步
          async: true,
          // sendAndForget: true
        },
        body: properties.map(property => property.id)
      }

      getDeviceRealtimeProperties(deviceId, props)
        .then(({ data }) => {
          if (data === 'error.code.client_offline') {
            this.$modal.msgWarning('设备离线')
            return
          }
          if (data === 'error.code.request_handling') {
            this.$modal.msgSuccess('请求处理中')
            return
          }
          if (data === 'error.code.time_out') {
            this.$modal.msgSuccess('请求超时')
            return
          }

          if (JSON.stringify(data) === '{}') {
            this.$modal.msgSuccess('已发出')
            return
          }

          console.warn(data)

        })
        .catch(() => {
          this.$modal.msgError('请求失败')
        })
    },

    /** 功能添加按钮操作 */
    handleFunctionsAdd() {
      this.$refs.functionsAddEdit.handleAdd();
    },

    /** 事件添加按钮操作 */
    handleEventsAdd() {
      this.$refs.eventsAddEdit.handleAdd();
    },

    /** 事件添加按钮操作 */
    handleTagsAdd() {
      this.$refs.tagsAddEdit.handleAdd();
    },

    /** 查看物模型操作 */
    handlePhysicalModelView() {
      this.$refs.viewPhysicalModel.handleCheck(this.deviceDetailInfo.metadata);
    },

    /** 提交属性表单数据 */
    submitProperties(formData, callBack) {
      let metadata = JSON.parse(this.deviceDetailInfo.metadata);
      this.submitForm(metadata, metadata.properties, formData, callBack);
    },

    /** 提交功能表单数据 */
    submitFunctions(formData, callBack) {
      let metadata = JSON.parse(this.deviceDetailInfo.metadata);
      this.submitForm(metadata, metadata.functions, formData, callBack);
    },

    /** 提交事件表单数据 */
    submitEvents(formData, callBack) {
      let metadata = JSON.parse(this.deviceDetailInfo.metadata);
      this.submitForm(metadata, metadata.events, formData, callBack);
    },

    /** 提交标签表单数据 */
    submitTags(formData, callBack) {
      let metadata = JSON.parse(this.deviceDetailInfo.metadata);
      this.submitForm(metadata, metadata.tags, formData, callBack);
    },

    // 提交表单
    submitForm(deriveMetadata, list, formData, callBack) {
      utils.arrayPutValue(list, formData);
      const metadata = JSON.stringify(deriveMetadata);
      // 更新数据
      updateMetadata(this.deviceId, metadata).then(() => {
        // 更新缓存数据
        this.$store.commit("DEVICE_DETAIL_INFO", { metadata: metadata, independentMetadata: true });
        if (typeof callBack === 'function') {
          callBack()
        }
      })
    },

    /** 提交协议支持 */
    submitProtocolStandby(id, jsonData, callback) {

      let protocolStandby = this.deviceDetailInfo.protocolStandby

      if (!protocolStandby) {
        protocolStandby = '{}'
      }

      let protocolStandbyObject = JSON.parse(protocolStandby)
      if (!jsonData.id) {
        delete protocolStandbyObject[id]
      }else {
        protocolStandbyObject[id] = jsonData
      }
      let protocolStandbyString = JSON.stringify(protocolStandbyObject)

      updateProtocolStandby(this.deviceId, protocolStandbyString).then(() => {
        this.$store.commit('DEVICE_DETAIL_INFO', {
          protocolStandby: protocolStandbyString,
          independentProtocolStandby: true
        })
        if (typeof callback === 'function') {
          callback()
        }
      })
    },

  }
}
</script>

<style lang="scss" scoped>

// 物模型操作按钮
.physical-model-button {
  float: right;
  right: 15px;
  position: absolute;
  z-index: 1000
}

// 属性卡片头
.card-header {
  margin-top: 5px;
  margin-bottom: 5px;

  // 添加操作按钮
  .add-button {
    float: right;
    top: -6px;
    position: relative
  }
}

</style>
